from fastapi import APIRouter, HTTPException, Query, Depends
from typing import List, Optional
from sqlalchemy.orm import Session
from app.core.database import get_db

router = APIRouter()

@router.get("/list")
async def get_servers(
    page: int = Query(1, ge=1, description="页码"),
    limit: int = Query(20, ge=1, le=100, description="每页数量"),
    name: Optional[str] = Query(None, description="服务器名称模糊搜索"),
    status: Optional[str] = Query(None, description="状态筛选"),
    db: Session = Depends(get_db)
):
    """获取服务器列表 - 统一返回格式"""
    try:
        # 返回模拟数据，实际项目中应从数据库查询
        servers = [
            {
                "id": 1,
                "name": "主服务器",
                "ip": "192.168.1.100",
                "port": 8080,
                "status": "online",
                "cpu_usage": 45.2,
                "memory_usage": 67.8,
                "disk_usage": 23.5,
                "uptime": "2天3小时",
                "last_update": "2024-01-15 14:30:00"
            },
            {
                "id": 2,
                "name": "备用服务器",
                "ip": "192.168.1.101",
                "port": 8080,
                "status": "online",
                "cpu_usage": 32.1,
                "memory_usage": 45.6,
                "disk_usage": 15.2,
                "uptime": "1天8小时",
                "last_update": "2024-01-15 14:30:00"
            }
        ]
        
        # 应用搜索和状态筛选
        filtered_servers = servers
        if name:
            filtered_servers = [s for s in filtered_servers if name.lower() in s["name"].lower()]
        if status:
            filtered_servers = [s for s in filtered_servers if s["status"] == status]
            
        # 分页
        total = len(filtered_servers)
        start = (page - 1) * limit
        end = start + limit
        paginated_servers = filtered_servers[start:end]
        
        return {
            "code": 200,
            "data": {
                "items": paginated_servers,
                "total": total
            },
            "message": "success"
        }
        
    except Exception as e:
        return {
            "code": 500,
            "data": {
                "items": [],
                "total": 0
            },
            "message": f"获取服务器列表失败: {str(e)}"
        }

@router.post("/")
async def create_server(server_data: dict):
    """创建服务器 - 兼容前端接口"""
    return {"success": True, "id": 2, **server_data}

@router.put("/{server_id}")
async def update_server(server_id: int, server_data: dict):
    """更新服务器 - 兼容前端接口"""
    return {"success": True, "id": server_id, **server_data}

@router.delete("/{server_id}")
async def delete_server(server_id: int):
    """删除服务器 - 兼容前端接口"""
    return {"success": True, "message": "服务器已删除"}